// 实现这个项目的构建任务
const { src, dest, parallel, series, watch } = require('gulp')

const del = require('del')
const browserSync = require('browser-sync')

const loadPlugins = require('gulp-load-plugins')

const plugins = loadPlugins()
const bs = browserSync.create()

// 1.定义变量cwd,process.cwd()方法会返回当前命令行所在的工作目录,假如这个模块在dome1项目中运行,那么工作目录就是dome1目录
const cwd = process.cwd()
//2.载入配置文件
let config ={
  //default,假设存在默认成员就不能直接替换config,需要通过Object.assign去拷贝对象
  // 配置默认的抽象路径
  
}

try {//因为require一个不存在的地址会报错所以我们用try_catch包装一下
  const loadConfig = require(`${cwd}/pages.config.js`)
  config = Object.assign({ },config,loadConfig)
} catch (error) {
  console.log(error)
}

const clean = () => {
  return del(['dist', 'temp'])
}

const style = () => {
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp'))

}

const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))

}

const page = () => {
  return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({ data:config.data, defaults: { cache: false } })) // 防止模板缓存导致页面不能及时更新
    .pipe(dest('temp'))

}

const image = () => {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const font = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const extra = () => {
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}
//eslint检测js代码规范
const eslint = ()=>{
    return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.eslint({
        rules: {
            'my-custom-rule': 1,
            'strict': 2
        },
        globals: [
            'jQuery',
            '$'
        ],
        envs: [
            'browser'
        ]
    }))
    .pipe(plugins.eslint.formatEach('compact', process.stderr))
}
// 检测css代码中的错误
const sasslint = ()=>{
    src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.sassLint())
    .pipe(plugins.sassLint.format())
    .pipe(plugins.sassLint.failOnError())
}
const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)

  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload)

  bs.init({
    notify: false,
    port: 2080,
    // open: false,
    files: 'dist/**',
    server: {
      baseDir: ['temp', 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

const useref = () => {
  // 在构建生产环境使用的项目时处理html中node_modules的文件的依赖
  return src('temp/*.html', { base: 'temp' })
    .pipe(plugins.useref({ searchPath: ['temp', '.'] }))
    // html js css
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    })))
    .pipe(dest('dist'))
}
const deployPro = (done)=>{
    //这里应该是构建成功后部署到服务器。目前没有服务器，暂时是空的
    const argv = process.argv;
    if(argv.includes('--production')){
        done()
    }else{
        done()
    }
}
const lint = parallel(eslint,sasslint)

const compile = parallel(style, script, page)

// 上线之前执行的任务
const build =  series(
  clean,
  parallel(
    series(compile, useref),
    image,
    font,
    extra
  )
)

const start = series(compile, serve)


const deploy = series(build,deployPro)

module.exports = {
  clean,
  serve,
  build,
  start,
  lint,
  deploy
}
